<%@ page language="java" import="com.alibaba.fastjson.JSONObject" pageEncoding="UTF-8" %>
<%@ page import="org.apache.axis.encoding.Base64" %>
<%@ page import="weaver.conn.RecordSet" %>
<%@ page import="weaver.docs.webservices.DocAttachment" %>
<%@ page import="weaver.docs.webservices.DocInfo" %>
<%@ page import="weaver.docs.webservices.DocServiceImpl" %>
<%@ page import="weaver.general.BaseBean" %>
<%@ page import="weaver.general.Util" %>
<%@ page import="weaver.hrm.HrmUserVarify" %>
<%@ page import="weaver.hrm.User" %>
<%@ page import="weaver.hrm.resource.ResourceComInfo" %>
<%@ page import="weaver.soa.workflow.request.MainTableInfo" %>
<%@ page import="weaver.soa.workflow.request.Property" %>
<%@ page import="weaver.soa.workflow.request.RequestInfo" %>
<%@ page import="weaver.soa.workflow.request.RequestService" %>
<%@ page import="weaver.workflow.request.RequestComInfo" %>
<%@ page import="weaver.workflow.workflow.WorkflowComInfo" %>
<%@ page import="java.io.ByteArrayOutputStream" %>
<%@ page import="java.io.File" %>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="weaver.common.DateUtil" %>
<%--获取流水号--%>
<%
    JSONObject jsonData = new JSONObject();
    String mailId = Util.null2String( request.getParameter( "mailId" ) );
    String curdate = DateUtil.getCurrentDate();
    User user = HrmUserVarify.getUser( request, response );
    int userid = user.getUID();
    String username = user.getLastname();
    String requestname ="邮件审批流程-"+username+"-"+curdate;
    RecordSet rs = new RecordSet();
    rs.executeQuery( "select id,resourceid,`SUBJECT` as title,mit_uuid from mailresource where id=?", mailId );
    rs.next();
    String resourceid = Util.null2String( rs.getString( "resourceid" ) );
    String title = Util.null2String( rs.getString( "title" ) );
    String mit_uuid = Util.null2String( rs.getString( "mit_uuid" ) );
    String consignee = getConsignee(mit_uuid);
    String mailcontent = getContent(mailId);
    String docids = "";
    int secid = 88;
    rs.executeQuery( "select filename,filerealpath from mailresourcefile where mailid=?", mailId );
    while (rs.next()) {
        String filename = Util.null2String( rs.getString( "filename" ) );
        String filerealpath = Util.null2String( rs.getString( "filerealpath" ) );
        int docid = createDoc( user, filename, filerealpath, secid );
        docids += "".equals( docids ) ? docid : "," + docid;
    }
    Map<String, String> requestMainMap = new HashMap<>(  );
    requestMainMap.put( "fjr",resourceid );
    requestMainMap.put( "sjr",consignee );
    requestMainMap.put( "zt",title );
    requestMainMap.put( "nr",mailcontent );
    requestMainMap.put( "fj",docids );
    String requestid = WorkflowCreateByRequestMap(userid+"","3",requestname,"1",requestMainMap);
    jsonData.put( "requestid", requestid );
    jsonData.put( "msg", expoundRequest(requestid));
    out.print( jsonData.toJSONString() );
%>
<%!
    BaseBean baseBean = new BaseBean();

    //创建流程方法
    public String WorkflowCreateByRequestMap(String creatorId, String workflowId, String requestName, String IsNextFlow, Map<String, String> requestMainMap) {
        baseBean.writeLog( "-----创建流程传递的参数个数--------" );
        baseBean.writeLog( "creatorId:" + creatorId );
        baseBean.writeLog( "workflowId:" + workflowId );
        baseBean.writeLog( "requestName:" + requestName );
        baseBean.writeLog( "IsNextFlow:" + IsNextFlow );

        String requestid = "";
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setCreatorid( creatorId );//创建人Id
        requestInfo.setWorkflowid( workflowId );//工作流Id
        requestInfo.setDescription( requestName );//请求标题
        if ("0".equals( IsNextFlow )) {
            requestInfo.setIsNextFlow( IsNextFlow );
        }

        //主表字段
        MainTableInfo mainTableInfo = new MainTableInfo();
        Property[] propertyArray = new Property[requestMainMap.size()];
        int p = 0;
        for (Map.Entry<String, String> entry : requestMainMap.entrySet()) {
            propertyArray[p] = new Property();
            propertyArray[p].setName( Util.null2String( entry.getKey() ) );
            propertyArray[p].setValue( Util.null2String( entry.getValue() ) );
            baseBean.writeLog( "\r\n---p=" + p + "---Key=" + entry.getKey() + "---Value=" + entry.getValue() );
            p++;
        }
        baseBean.writeLog( "-----创建流程传递的参数个数p=" + p );
        mainTableInfo.setProperty( propertyArray );
        requestInfo.setMainTableInfo( mainTableInfo );
        RequestService service = new RequestService();
        try {
            //流程
            try {
                requestid = service.createRequest( requestInfo );//创建请求id
            } catch (Exception e) {
                baseBean.writeLog( "=======" + e.getMessage() );
            }
            //String userId = requestInfo.getLastoperator();//请求最后的操作者
            //记录日志
            StringBuffer sbf = new StringBuffer( "\r\n-----xwd创建工作流记录日志开始" );
            WorkflowComInfo wfcif = new WorkflowComInfo();
            RequestComInfo rcif = new RequestComInfo();
            ResourceComInfo rscif = new ResourceComInfo();
            sbf.append( "\r\n-----姓名:" + rscif.getLastname( rcif.getRequestCreater( requestid ) ) );
            sbf.append( "\r\n-----时间:" + rcif.getRequestCreateTime( requestid ) );
            sbf.append( "\r\n-----创建流程:" + wfcif.getWorkflowname( workflowId ) );
            sbf.append( "\r\n-----请求:" + rcif.getRequestname( requestid ) );
            sbf.append( "\r\n-----请求:" + requestid );
            sbf.append( "\r\n-----创建工作流记录日志结束" );
            baseBean.writeLog( sbf.toString() );
        } catch (Exception e) {
            baseBean.writeLog( "错误：" + e );
        }
        return requestid;
    }

    //创建流程返回数字字典
    public String expoundRequest(String requestid) {
        baseBean.writeLog( "--------------requestid:" + requestid );
        String dec = "";
        int ireqid = Util.getIntValue( requestid, 0 );
        if (ireqid > 0) {

        } else if (ireqid == -1) {
            dec = "创建流程失败";
        } else if (ireqid == -2) {
            dec = "用户没有流程创建权限";
        } else if (ireqid == -3) {
            dec = "创建流程基本信息失败";
        } else if (ireqid == -4) {
            dec = "保存表单主表信息失败";
        } else if (ireqid == -5) {
            dec = "更新紧急程度失败";
        } else if (ireqid == -6) {
            dec = "流程操作者失败";
        } else if (ireqid == -7) {
            dec = "流转至下一节点失败";
        } else if (ireqid == -8) {
            dec = "节点附加操作失败";
        }
        return dec;
    }

    public String getContent(String mailid){
        RecordSet rs = new RecordSet(  );
        rs.executeQuery("select mailcontent from mailcontent where mailid=?",mailid);
        rs.next();
        String mailcontent = Util.null2String( rs.getString( "mailcontent" ) );
        return mailcontent;
    }

    //获取收件人
    public String getConsignee(String mit_uuid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select GROUP_CONCAT(RESOURCEID,'') as consignee from mailresource where" +
                " mit_uuid=? and MR_UUID is null", mit_uuid );
        rs.next();
        String consignee = Util.null2String( rs.getString( "consignee" ) );
        return consignee;
    }

    //创建文档
    public static int createDoc(User user, String rawFileName, String path, int secid) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog( ">>>>>>createDocs>>>>>>" );
        int docid = -1;
        DocServiceImpl docserviceimpl = new DocServiceImpl();
        DocInfo doc = new DocInfo(); //创建文档
        String keyword = ""; //文档内容
        try {
            DocAttachment[] docattachment = new DocAttachment[1];
            baseBean.writeLog( ">>>>>rawFileName=" + rawFileName );
            String filetype = "";
            if (rawFileName.lastIndexOf( "." ) > -1) {
                filetype = rawFileName.substring( rawFileName.lastIndexOf( "." ) + 1 );
            }
            byte[] content = new byte[102400];
            // 上传附件，创建html文档
            content = null;
            try {
                int byteread;
                byte data[] = new byte[1024];
                InputStream input = new FileInputStream( new File( path ) );
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                while ((byteread = input.read( data )) != -1) {
                    outputStream.write( data, 0, byteread );
                    outputStream.flush();
                }
                content = outputStream.toByteArray();
                baseBean.writeLog( ">>>>>content=" + content.length);
                input.close();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            DocAttachment da = new DocAttachment();
            da.setFilename( rawFileName );//附件标题
            da.setFilecontent( Base64.encode( content ) ); //附件内容
            da.setFiletype( filetype ); //imagefiletype
            da.setImagefilename( rawFileName );// 附件标题
            da.setIszip( 1 );//是否压缩
            da.setIsAesEncrype( 0 );//是否加密
            da.setAesCode( "0" );
            da.setIsextfile( "1" ); //附件是否是office类型

            if (filetype.equalsIgnoreCase( "doc" )) {
                da.setDocfiletype( "3" );
            } else if (filetype.equalsIgnoreCase( "xls" )) {
                da.setDocfiletype( "4" );
            } else if (filetype.equalsIgnoreCase( "ppt" )) {
                da.setDocfiletype( "5" );
            } else if (filetype.equalsIgnoreCase( "wps" )) {
                da.setDocfiletype( "6" );
            } else if (filetype.equalsIgnoreCase( "docx" )) {
                da.setDocfiletype( "7" );
            } else if (filetype.equalsIgnoreCase( "xlsx" )) {
                da.setDocfiletype( "8" );
            } else if (filetype.equalsIgnoreCase( "pptx" )) {
                da.setDocfiletype( "9" );
            } else {
                da.setDocfiletype( "2" );
            }
            docattachment[0]= da;
            keyword = rawFileName;
            doc.setAttachments( docattachment );
            doc.setSeccategory( secid );//子目录id
            doc.setDocSubject( keyword );//标题
            doc.setDoccontent( "" );//文档内容
            /*文档属性*/
            doc.setDocType( 1 );
            //文档状态
            doc.setDocStatus( 1 );
            doc.setDocStatusStr( "正常" );
            //新闻类型
            doc.getDocPublishType();
            doc.setPublishable( "文档" );
            doc.setKeyword( keyword );
            docid = docserviceimpl.createDocByUser( doc, user );
            baseBean.writeLog( ">>>>>docid=" + docid );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return docid;
    }
%>